/**
 * 
 */
package com.augurit.wf.app.notice.handler;

import java.util.List;

import org.jbpm.api.model.OpenExecution;
import org.jbpm.api.task.Assignable;
import org.jbpm.api.task.AssignmentHandler;
import org.jbpm.pvm.internal.env.EnvironmentImpl;
import org.springframework.beans.factory.annotation.Autowired;

import com.augurit.common.dao.AcRoleDao;
import com.augurit.common.dao.AcUserRoleDao;
import com.augurit.common.dao.OmUserDao;
import com.augurit.common.dao.OmUserOrgDao;
import com.augurit.common.entity.OmUser;
import com.augurit.common.entity.OmUserOrg;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.HqlUtils;
import com.augurit.wf.common.web.WfAction;

/**
 * 类功能:自定义参与者
 * 2011-4-1
 */
public class AssignTask implements AssignmentHandler{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void assign(Assignable assignable, OpenExecution execution) {
		
		//dao与service的注入方式
		OmUserDao userDao = (OmUserDao)EnvironmentImpl.getCurrent().get(OmUserDao.class);
		AcRoleDao roleDao = (AcRoleDao)EnvironmentImpl.getCurrent().get(AcRoleDao.class);
		AcUserRoleDao userRoleDao = (AcUserRoleDao)EnvironmentImpl.getCurrent().get(AcUserRoleDao.class);
		
		//************自己的业务逻辑 开始************
		String key = "$SYSVAR_ASSIGNEE_checking";
		String roleCode="zf_zddz"; //系统中队队长编码
		String hql="select ps.roleId from AcRole ps where ps.roleCode='"+roleCode+"'";
		List<Long> roleIds = roleDao.find(hql);//通过编码获取角色编号
		String loginName = execution.getVariable(key).toString();
		OmUser userEntity = userDao.get(loginName);
		Long userId= userEntity.getUserId();//获取用户id
		System.out.println("userId:"+userId);
		
		OmUserOrgDao userOrgDao = (OmUserOrgDao)EnvironmentImpl.getCurrent().get(OmUserOrgDao.class);
		List<OmUserOrg> uoList=userOrgDao.getByUserId(userId);//根据用户id获取组织架构
		Long[] orgIds=new Long[uoList.size()];
		for(int i=0;i<uoList.size();i++){
			orgIds[i] = uoList.get(i).getOrgId();
		}
		
		Long[] userIds = userOrgDao.getUserIdsByOrgIds(orgIds);// 根据机构id数组获取其下的所有的用户
		
		hql="select ps.userId from AcUserRole ps where ps.roleId="+roleIds.get(0)+" and ";//根据角色id和用户id获取用户id
		String condition = HqlUtils.buildOrCondition("ps", "userId", userIds);
		hql += condition;
		List<Long> userIdList = userRoleDao.find(hql);
		
		String assignee="";
		if(userIdList!=null){
			List<OmUser> users = userDao.findByIds(userIdList);
			for(OmUser user : users){
				assignee+=user.getUserCode()+",";
			}
		}
		
		assignee=assignee.substring(0, assignee.length()-1);
		
		//************自己的业务逻辑 结束************
		
		//将获取的assignee设置到任务中
		assignable.setAssignee(assignee);
	  }
	
}
